import React, { Component } from 'react'
import Header from './Header'
import Content from './Content'
import {ListProps} from '../shoppmodel/Shoppingcar'
import Footer from './Footer'

interface Istate {
    checkAll:boolean,
    totalnum:number,
    totalprice:number,
    list:Array<ListProps>
}
export default class ShoppingCar extends Component<any,Istate> {
  constructor(props:any){
            super(props);
            this.state={
              totalnum:0,
              totalprice:0,
              checkAll:false,
              list:[{id:1,name:"商品一",price:100,num:1,checked:false},
              {id:2,name:"商品二",price:100,num:2,checked:false},
              {id:3,name:"商品三",price:100,num:3,checked:false},
              {id:4,name:"商品四",price:100,num:4,checked:false}
          ]
            }
  }
  checkCheckAll=()=>{
    this.setState({
      checkAll:this.state.list.length?this.state.list.every(item=>item.checked):false,
    },()=>{this.totals()})
  }
  setCheckAll=(flag:boolean)=>{//全选
    this.setState({
      checkAll:flag,
      list:this.state.list.map(info=>{
        info.checked= flag
        return info
    })
    },()=>{this.checkCheckAll()})
  }
  calc = (id:number,num:number)=>{//计算
          this.setState({
              list:this.state.list.map(item=>{
                if(item.id==id){
                  item.num+=num
                }
                return item
              })
          },()=>{this.totals()})
  }
  setCheckOne=(id:number,flag:boolean)=>{//单选
          this.setState({
            list:this.state.list.map(item=>{
              if(item.id==id){
                item.checked = flag
              }
              return item
            })
          },()=>{this.checkCheckAll()})
  }
  delid = (id:number)=>{
    this.setState({
      list:this.state.list.filter(item=>item.id!=id)
      
        },()=>{this.checkCheckAll()})
  }
  totals=()=>{
    let num =0;
    let price = 0;
    let list = this.state.list.filter(item=>item.checked)
    if(list.length){
      list.forEach(info=>{
        num+=info.num
        price+=info.num*info.price
      })
    }
    this.setState({
      totalnum:num,
      totalprice:price
    })
  }

  render() {
    return (
      
      <><div>

        {this.props.num}
        {/* 这里就是将数据显示在页面上使用getState的方法 */}
        <hr></hr>
        <button onClick={()=>{this.props.addNum(1000)}}>-</button>
        {/* //这里里面就可以直接调用函数了 */}
        {/* //这里是强制走render让页面开始渲染变成响应式 */}
        {/* //不然在其他页面数据改变这个页面数据不会改变 */}

      </div><div className='table'>
          <Header checkAll={this.state.checkAll} setCheckAll={this.setCheckAll}></Header>
          <Content delid={this.delid} calc={this.calc} list={this.state.list} setCheckOne={this.setCheckOne}></Content>
          <Footer totalnum={this.state.totalnum} totalprice={this.state.totalprice}></Footer>
        </div></>
      
    )
  }
}